package com.example.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;

public class ProxyTest {
    public static void main(String[] args) {
        var elements = new Object[1000];
        for(int i = 0; i < 1000; i++){
            Integer value = i + 1;
            var handler = new TraceHandler(value);
            Object proxy = Proxy.newProxyInstance(
                    ClassLoader.getSystemClassLoader(),
                    new Class[]{Comparable.class},    //每个元素对应需要实现的各个接口
                    handler
            );
            elements[i] = proxy;
        }

        Integer index = new Random().nextInt(elements.length) + 1;
        //返回索引
        int result = Arrays.binarySearch(elements, index);
        if(result >= 0){
            System.out.println(elements[result]);
        }
    }
}

//打印调用过程的调用处理器
class TraceHandler implements InvocationHandler{

    private Object target;

    public TraceHandler(Object t) {
        this.target = t;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.print(target);
        System.out.print("." + method.getName() + "(");
        if(args != null){
            for(int i = 0; i < args.length; i++){
                System.out.print(args[i]);
                if(i < args.length - 1){
                    System.out.print(", ");
                }
            }
        }
        System.out.println(")");
        //调用实际的方法
        return method.invoke(target, args);
    }
}
